package bgw

import (
	"context"
	"errors"
	"strconv"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/bgw"
	"github.com/bytedance/sonic/decoder"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Bgw{
		MerchantId: config.MerchantId,
		Url:        config.Url,
		AppId:      config.AppId,
		AppCode:    config.AppCode,
		AppSecret:  config.SecretKey,
		NotifyUrl:  config.NotifyUrl,
	}
}

type Bgw struct {
	MerchantId string
	AppId      string
	AppCode    string
	AppSecret  string
	Url        string
	NotifyUrl  string
}

type Resp struct {
	Code  int64  `json:"code"`
	Msg   string `json:"msg"`
	Error string `json:"error"`
	Data  any    `json:"data"`
}

// 代收订单创建
func (p *Bgw) Pay(ctx context.Context, req map[string]any) (resp base.PayResponse, err error) {
	b := bgw.Bgw{
		MerchantId: p.MerchantId,
		AppId:      p.AppId,
		AppCode:    p.AppCode,
		AppSecret:  p.AppSecret,
		NotifyUrl:  p.NotifyUrl,
		Url:        p.Url,
	}
	params := bgw.PaymentReq{
		OuterNo:   req["orderNo"].(string),
		UserId:    strconv.Itoa(int(req["user_id"].(int64))),
		Currency:  1005,
		Amount:    int64(req["amount"].(float64) * 100),
		Scale:     2,
		NotifyUrl: p.NotifyUrl,
	}
	result, err := bgw.NewBgw(b).Payment(ctx, params)
	if err != nil {
		return
	}

	resp = base.PayResponse{
		Url:     result.Data.(map[string]any)["payURL"].(string),
		OrderNo: result.Data.(map[string]any)["orderNo"].(string),
	}
	return
}

// 发送请求
func sendRequest(ctx context.Context, url string, params map[string]any) (resp Resp, err error) {
	output, err := base.SendPostJson(ctx, url, params)
	if err != nil {
		return resp, err
	}
	dc := decoder.NewDecoder(output)
	dc.UseNumber()
	dc.Decode(&resp)
	if resp.Code != 0 {
		return resp, errors.New(resp.Msg)
	}
	return
}
